package com.back.demo.exception;

import com.back.demo.common.CommonResult;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

import static com.back.demo.controller.myVO.errorBeanEnum.BasicResponseBeanEnum.AUTHENTICATION_ERROR;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 处理 SpringMVC 参数校验不正确
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public CommonResult<?> methodArgumentNotValidExceptionExceptionHandler(MethodArgumentNotValidException exception) {
        log.warn("[methodArgumentNotValidExceptionExceptionHandler]", exception);
        FieldError fieldError = exception.getBindingResult().getFieldError();
        assert fieldError != null; // 断言，避免告警
        return CommonResult.error(400, String.format("请求参数不正确:%s", fieldError.getDefaultMessage()));
    }

    @ExceptionHandler(value = GlobalException.class)
    public CommonResult<?> globalExceptionHandler(GlobalException exception) {
        log.warn("[globalExceptionHandler]", exception);
        return CommonResult.error(exception.getResponseBeanEnum());
    }

    @ExceptionHandler(value = ExpiredJwtException.class)
    public CommonResult<?> handleJwtTokenExpiredException(HttpServletResponse response, ExpiredJwtException exception) throws IOException {
        // 设置HTTP响应状态码为401
        response.setStatus(HttpStatus.UNAUTHORIZED.value());

        // 注释掉的部分适合返回类型void的情况
/*        // 设置响应内容类型为JSON
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);

        // 构建一个简单的JSON响应体
        String responseBody = "{\"error\":\"TokenExpired\",\"message\":\"JWT token has expired.\"}";

        // 将响应体写入HttpServletResponse
        try (PrintWriter out = response.getWriter()) {
            out.print(responseBody);
        }*/
        return CommonResult.error(AUTHENTICATION_ERROR);
    }
}